import { Button, Modal, Form, Input, Select, DatePicker } from 'antd';
import { useState, useContext, useEffect } from 'react';
import moment from 'moment';

import { context } from '../index';

const Index = () => {
  const { isModalOpen, addStudent, modalClose, type, itemData, editStudent } =
    useContext(context);
  const [form] = Form.useForm();
  const handleOk = () => {
    if (type === 'add') {
      form
        .validateFields()
        .then((values) => {
          addStudent({
            ...values,
            birthday: new Date(values.birthday).getTime(),
          });
          form.resetFields();
        })
        .catch((err) => {
          return err;
        });
    } else {
      form
        .validateFields()
        .then((values) => {
          editStudent({
            ...values,
            birthday: new Date(values.birthday).getTime(),
            id: itemData._id,
          });
          form.resetFields();
        })
        .catch((err) => {
          return err;
        });
    }
  };

  const close = () => {
    form.resetFields();
    modalClose();
  };

  useEffect(() => {
    if (JSON.stringify(itemData) !== '{}') {
      const obj = {
        ...itemData,
        birthday: moment(itemData.birthday),
      };
      form.setFieldsValue(obj);
    }
  }, [itemData]);

  return (
    <Modal
      title={type === 'add' ? '新增学员' : '编辑学员'}
      open={isModalOpen}
      onOk={handleOk}
      onCancel={close}
    >
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        initialValues={{ remember: true }}
        autoComplete="off"
      >
        <Form.Item
          label="姓名"
          name="name"
          rules={[{ required: true, message: 'Please input your name!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="性别"
          name="sex"
          rules={[{ required: true, message: 'Please choose your sex!' }]}
        >
          <Select
            allowClear
            options={[
              {
                value: '1',
                label: '男',
              },
              {
                value: '2',
                label: '女',
              },
            ]}
          />
        </Form.Item>

        <Form.Item
          label="城市"
          name="city"
          rules={[{ required: true, message: 'Please input your city!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="生日"
          name="birthday"
          rules={[{ required: true, message: 'Please input your city!' }]}
        >
          <DatePicker />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default Index;
